package utils;


import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;



import java.io.IOException;
import java.util.Vector;

/////////////////////////////
import	ClassPack.Class;
import  ClassPack.ClassDiagram;
////////////////////////////

public class ClassDiagramFileReader {

	private String 			m_fileName;

	
	
	public ClassDiagramFileReader(String FileName) {
	
		m_fileName =FileName;
	}
	
	private ClassDiagram createClassDiagram(Element root) {
		
		ClassDiagram cd = new ClassDiagram();
		cd.setName(root.getName());
		Vector<Element> classes = new Vector<Element>(root.getChildren());
	
		addAllClasses(cd , classes);
	
		
		
		for (int i=0 ; i < classes.size() ; i ++) {
			connectClasses(cd , classes.elementAt(i) , i );
		}
		System.out.println(cd);
		return cd;
	}

	private void connectClasses(ClassDiagram cd, Element class_elem, int i) {
		
		Class connected_class = cd.getM_classes().elementAt(i);
		Vector<Element> ref_classes = new Vector<Element> 
						(class_elem.getChild("Refenenced_classes").getChildren());
		
	
		for (Element ref_class : ref_classes) {
			Class c = cd.getClassByName(ref_class.getName());
			connected_class.addReferencedClass(c);
		}
		Vector<Element> inhereted_interfaces = 
			ref_classes = new Vector<Element> 
		(class_elem.getChild("inhereted_interfaces").getChildren());
		
		for (Element in_interface : inhereted_interfaces) {
			Class c = cd.getClassByName(in_interface.getName());
			connected_class.add_inhereted_interface(c);
		}
	
		//	System.out.println(cd);
	
	}

	private void addAllClasses(ClassDiagram cd, Vector<Element> classes) {
		
		for ( Element e : classes ) {
			Class tmp_class = new Class();
			tmp_class.setM_class_name(e.getName());
			cd.addClass(tmp_class);
		}
		
	}

	public ClassDiagram CreateClassDiagram(){
		
		  SAXBuilder builder = new SAXBuilder();
		     
		    try {
		      Document doc = builder.build(m_fileName);
		      Element root = doc.getRootElement();
		      return createClassDiagram(root);      
		    }
		    // indicates a well-formedness error
		    catch (JDOMException e) { 
		      System.out.println(m_fileName + " is not well-formed.");
		      System.out.println(e.getMessage());
		      return null;
		    }  
		    catch (IOException e) { 
		      System.out.println(e);
		      return null;
		    }  
		  
		  
		
	}

	public static void main(String[] args) {
	
	   new ClassDiagramFileReader("sami.xml").CreateClassDiagram();
	
	  }

	
}
